package com.lsj.controller;

import com.google.common.collect.Lists;
import com.lsj.dao.CloudDiskDao;
import com.lsj.entity.CloudDiskEntity;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
public class CloudDiskController {

    @Autowired
    CloudDiskDao cloudDiskDao;

    /*根据ID查询对应的数据*/
    @GetMapping("/get/CloudDisk/{id}")
    public Optional<CloudDiskEntity> getById(@PathVariable String id){
        Optional<CloudDiskEntity> diskEntity = cloudDiskDao.findById(id);
        return diskEntity;
    }


    /*根据关键字实现模糊查询*/
    @PostMapping("/like/CloudDisk")
    public List<CloudDiskEntity> like(String name){
        BoolQueryBuilder builder = QueryBuilders.boolQuery();//bool组合查询
        if(!StringUtils.isEmpty(name)){
            MatchQueryBuilder match = QueryBuilders.matchQuery("name", name);
            builder.must(match);
        }
        Iterable<CloudDiskEntity> search = cloudDiskDao.search(builder);
        ArrayList<CloudDiskEntity> cloudDisks = Lists.newArrayList(search);
        return cloudDisks;
    }


    /*根据关键字实现模糊查询并实现分页*/
    @PostMapping("/like/CloudDisk/page")
    public Page<CloudDiskEntity> page(String name, @PageableDefault(page = 0,value = 2) Pageable pageable){
        BoolQueryBuilder builder = QueryBuilders.boolQuery();//bool组合查询
        if(!StringUtils.isEmpty(name)){
            MatchQueryBuilder match = QueryBuilders.matchQuery("name", name);
            builder.must(match);
        }
        Page<CloudDiskEntity> pages = cloudDiskDao.search(builder, pageable);
        System.out.println(pages.getTotalPages());
        return pages;
    }

}
